package dao

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

// http path
const (
	getVideoSchedulePath = "/api/v1/resource_center/cluster/schedule/video"
	getAISchedulePath    = "/api/v1/resource_center/cluster/schedule/ai"
)

type videoScheduleResp struct {
	ReturnCode   int               `json:"returnCode"`
	ErrorMessage string            `json:"errorMessage"`
	Result       map[string]string `json:"result"`
}

// GetVideoSchedule get video schedule
func (d *Dao) GetVideoSchedule(ctx context.Context) (map[string]string, error) {

	resResp := new(videoScheduleResp)

	resp, err := d.http().R().SetContext(ctx).Get(d.resCenterHost + getVideoSchedulePath)
	if err != nil {
		return nil, fmt.Errorf("HTTP request err: %s", err)
	}

	if resp.StatusCode() != http.StatusOK {
		if resp.StatusCode() == http.StatusNotFound {
			return make(map[string]string), nil
		}
		return nil, fmt.Errorf("HTTP status %s", resp.Status())
	}

	if err := json.Unmarshal(resp.Body(), resResp); err != nil {
		return nil, err
	}

	if resResp.ReturnCode != 0 {
		return nil, fmt.Errorf("Errcode: %d, Msg: %s", resResp.ReturnCode, resResp.ErrorMessage)
	}

	return resResp.Result, nil
}

type aiScheduleResp struct {
	ReturnCode   int               `json:"returnCode"`
	ErrorMessage string            `json:"errorMessage"`
	Result       map[string]string `json:"result"`
}

// GetAISchedule get ai schedule
func (d *Dao) GetAISchedule(ctx context.Context) (map[string]string, error) {

	resResp := new(aiScheduleResp)

	resp, err := d.http().R().SetContext(ctx).Get(d.resCenterHost + getAISchedulePath)
	if err != nil {
		return nil, fmt.Errorf("HTTP request err: %s", err)
	}

	if resp.StatusCode() != http.StatusOK {
		if resp.StatusCode() == http.StatusNotFound {
			return make(map[string]string), nil
		}
		return nil, fmt.Errorf("HTTP status %s", resp.Status())
	}

	if err := json.Unmarshal(resp.Body(), resResp); err != nil {
		return nil, err
	}

	if resResp.ReturnCode != 0 {
		return nil, fmt.Errorf("Errcode: %d, Msg: %s", resResp.ReturnCode, resResp.ErrorMessage)
	}

	return resResp.Result, nil
}
